package com.jiaquyun.jcps.ui.access

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.jiaquyun.jcps.R
import com.jiaquyun.jcps.app.AppConstance
import com.jiaquyun.jcps.app.BaseApplication
import com.jiaquyun.jcps.base.ViewModeActivity
import com.jiaquyun.jcps.mode.vm.AccessViewModel
import com.jiaquyun.jcps.popup.WebViewPopup
import com.jiaquyun.jcps.ui.main.ConfigActivity
import com.jiaquyun.jcps.ui.main.MainActivity
import com.lemlin.network.HttpServiceStatus
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_access.*
import kotlinx.android.synthetic.main.fragment_access_login.*
import kotlinx.android.synthetic.main.fragment_access_register.*
import kotlinx.android.synthetic.main.fragment_access_retrieve.*
import java.util.concurrent.TimeUnit

class AccessActivity : ViewModeActivity<AccessViewModel>() {

    companion object {
        fun open(activity: Activity) {
            val intent = Intent(activity, AccessActivity::class.java)
            activity.startActivity(intent)
        }
    }


    private val webViewPopup: WebViewPopup by lazy {
        WebViewPopup(
            context = this, onConfirm = {
                webViewPopup.dismiss()
                cbAccessSelect.isChecked = true
            }, onCancel = {
                webViewPopup.dismiss()
                cbAccessSelect.isChecked = false
                finish()
            })
    }

    override fun viewModel(): AccessViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_access

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, view = flAccessBar)
    }

    override fun initView() {

        ivAccessBack.setOnClickListener {
            this.onBackPressed()
        }

        if (BaseApplication.userToken().isNotEmpty() && BaseApplication.userInfo() != null) {
            MainActivity.open(activity = this)
            finish()
        } else {
            supportFragmentManager(LoginFragment.newInstance(), isToBackStack = false)
        }

        supportFragmentManager.registerFragmentLifecycleCallbacks(object :
            FragmentManager.FragmentLifecycleCallbacks() {
            override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
                super.onFragmentResumed(fm, f)
                tvAccessTitle.text = when (f) {
                    is RegisterFragment -> "注册"
                    is RetrieveFragment -> "找回密码"
                    else -> "登录"
                }
                ivAccessBack.visibility = when (f) {
                    is LoginFragment -> View.GONE
                    else -> View.VISIBLE
                }
            }
        }, false)

        tvAccessUserAgree.setOnClickListener {
            ConfigActivity.openUrl(
                activity = this,
                title = "用户协议",
                url = "https://mall.jiaquyun.cn/rider/common/get_article_details?id=10"
            )
        }

        tvAccessSecrecyAgree.setOnClickListener {
            ConfigActivity.openUrl(
                activity = this,
                title = "隐私协议",
                url = "https://mall.jiaquyun.cn/rider/common/get_article_details?id=14"
            )
        }

        val isAgree: Boolean = SPStaticUtils.getBoolean(AppConstance.BUNDLE_USER_AGREE, (false))

        if (!isAgree) {
            webViewPopup.showPopupWindow()
            webViewPopup.setOutSideDismiss(false)
            webViewPopup.setWindows(this)
        }

        cbAccessSelect.isChecked = isAgree
        cbAccessSelect.setOnCheckedChangeListener { _, isChecked ->
            SPStaticUtils.put(AppConstance.BUNDLE_USER_AGREE, isChecked)
        }
    }

    override fun initData() {
        viewModel.openPermissions(this)
    }

    override fun initViewMode() {
        viewModel.userInfoDataLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                MainActivity.open(activity = this)
                this.finish()
            }
        })
        viewModel.baseLiveData.observe(this, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                codeDownTime(tvLoginCodeGet)
            }
        })
        viewModel.permissionsLiveData.observe(this, Observer { isPermissions ->
            if (!isPermissions) toast("请到-设置-应用-开启相关权限！")
        })
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onBackPressed() {
        super.onBackPressed()
    }

    private fun supportFragmentManager(fragment: Fragment, isToBackStack: Boolean = true) {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (isToBackStack) {
            transaction.addToBackStack(null)
        }
        transaction.replace(R.id.flAccessBody, fragment)
        transaction.commit()
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.tvLoginRetrieve -> {
                //找回密码(切换至找回密码页面)
                supportFragmentManager(RetrieveFragment.newInstance())
            }
            R.id.tvLoginRegister -> {
                //注册(切换至注册页面)
                supportFragmentManager(RegisterFragment.newInstance())
            }
            R.id.tvLoginSubmit -> {
                viewModel.permissionsLiveData.value?.let { isPermissions ->
                    if (isPermissions) {
                        if (cbAccessSelect.isChecked) {
                            viewModel.mobileLogin(
                                etLoginCodePhone.text.toString(),
                                etLoginCodeCode.text.toString()
                            )
                        } else {
                            toast("请勾选《用户协议》《隐私协议》")
                        }
                    } else toast("请到-设置-应用-开启相关权限！")
                }
            }
            R.id.tvLoginCodeGet -> {
                //登录页获取验证码
                if (etLoginCodePhone.text.isNullOrEmpty()) {
                    toast("请输入有效的手机号")
                    return
                }
//                codeDownTime(view = view as TextView)
                viewModel.smsSend(etLoginCodePhone.text.toString())
            }
            R.id.tvRegisterCodeGet -> {
                //注册页获取验证码
                if (etRegisterCode.text.isNullOrEmpty()) {
                    toast("请输入有效的手机号")
                    return
                }
                codeDownTime(view = view as TextView)
            }
            R.id.tvRetrieveCodeGet -> {
                //找回密码页获取验证码
                if (etRetrieveCode.text.isNullOrEmpty()) {
                    toast("请输入有效的手机号")
                    return
                }
                codeDownTime(view = view as TextView)
            }
        }
    }


    /**
     * 获取验证码倒计时
     * */
    @SuppressLint("SetTextI18n")
    private fun codeDownTime(view: TextView) {
        val disposable: Disposable =
            Flowable.intervalRange(1, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext {
                    view.text = "剩余${60 - it}秒"
                }
                .doOnSubscribe {
                    view.isEnabled = false
                }
                .doOnComplete {
                    view.text = "获取验证码"
                    view.isEnabled = true
                }
                .subscribe()
        viewModel.dispose().add(disposable)
    }

}